#include "TcpServer.hpp"

void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << "serverip serverport" << endl;
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        cerr << "create sockfd err!" << endl;
        return 1;
    }


    //客户端需要绑定，但不需要显式绑定
    //UDP在首次发送数据时系统自动绑定
    //TCP在连接时系统自动绑定

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));//字符串 转 四字节

    //客户端专属接口：申请连接接口
    int n = connect(sockfd, (const sockaddr*)&server, sizeof(server));
    if(n < 0)
    {
        cerr << "connect err!" << endl;
        return 2;
    }

    //连接成功，可以发送消息了
    string message;
    while(true)
    {
        cout << "Please Entel@ ";
        getline(cin, message);
        write(sockfd, message.c_str(), message.size());//已发送给服务端

        char inbuffer[4096];
        int n = read(sockfd, inbuffer, sizeof(inbuffer));
        if(n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }
    }
    close(sockfd);
    return 0;
}